package com.custom.dao;

import com.custom.contants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSetMetaData;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

/**
 * @author wh
 * @Description
 * @date 2018/4/4 16:05
 */
@Repository("preDao")
public class PreJDBCTemplate implements PreDao {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    private String library;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public List<String> getTables() {
        String sql = "select table_name from information_schema.tables where table_schema='" + library + "' and table_type='base table'";
        List<String> tables = jdbcTemplate.query(sql, new PreMapper());
        return tables;
    }

    public ConcurrentHashMap<Object, Object> getMate(String table) {
        String sql = "select * from " + table;
        ConcurrentHashMap<Object, Object> metaMap = new ConcurrentHashMap<Object, Object>();
        try {
            ResultSet primaryKeys = jdbcTemplate.getDataSource().getConnection().getMetaData().getPrimaryKeys(null, null, table);
            LinkedList<String> keys = new LinkedList<String>();
            while (primaryKeys.next()) {
                keys.add(primaryKeys.getString(4));
            }
            Constants.primaryKeys.put(table, keys);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        SqlRowSetMetaData metaData = jdbcTemplate.queryForRowSet(sql).getMetaData();
        int columnCount = metaData.getColumnCount();

        for (int i = 0; i < columnCount; i++) {
            metaMap.put(metaData.getColumnName(i + 1), metaData.getColumnTypeName(i + 1));
        }

        return metaMap;
    }

    public void setLibrary(String library) {
        this.library = library;
    }

    private Logger log = Logger.getLogger(PreJDBCTemplate.class.getPackage().getName());
}